package cn.com.ddapp.ddm.fragment.base.order;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.adapter.OrderAdapter;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.order.Order;
import cn.com.ddapp.ddm.bean.order.OrderDetail;
import cn.com.ddapp.ddm.bean.order.OrderEntity;
import cn.com.ddapp.ddm.fragment.base.BaseFragment;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.Refreshable;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.ui.order.OrderDetailActivity;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TLog;
import cn.com.ddapp.ddm.widget.pulltorefresh.PullToRefreshLayout;
import cn.com.ddapp.ddm.widget.pulltorefresh.pullableview.PullableListView;

/**
 * Created by caopenghui on 2016-08-03.
 */
public class OrderListFragment extends BaseFragment implements View.OnClickListener,Refreshable{

    @BindView(R.id.pullToRefreshLayout)
    PullToRefreshLayout pullToRefreshLayout;
    @BindView(R.id.listview)
    PullableListView pullableListView;
    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;


    private List<Order> orderLists = new ArrayList<Order>();
    private List<OrderDetail> orderDetails = new ArrayList<>();
    private Integer st = 0;//数据起始
    private boolean isLastPage = false;
    private OrderAdapter orderAdapter;
    private Integer status = 0;

    @Override
    protected String getFragmentTag() {
        return OrderListFragment.class.getSimpleName();
    }

    public static OrderListFragment newInstance(int fragmentId) {
        Bundle bundle = new Bundle();
        bundle.putInt("fragmentId", fragmentId);
        OrderListFragment fragment = new OrderListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onClick(View view) {

    }

    /**
     * @param isShowProgress 是否显示加载框
     *@param isClearDatas 是否清空数据源
     * @param isFirst   是否第一次加载
     */
    private void requestData(final boolean isShowProgress, final boolean isClearDatas,final boolean isFirst) {

        if(isShowProgress){
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        }
        String userId = SPUtils.getStringData(getActivity(), SPUtils.USERID);


        final OkUtilCallback okUtilCallback =  new OkUtilCallback(mEmptyLayout) {
            @Override
            public void onMyResponse(String response, int id) {
                TLog.log(response);
                OrderEntity entity = gson.fromJson(response,OrderEntity.class);
                if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))&&entity.getLogin()){
                    mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                }else if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                }else if((isFirst)&&entity.getList().size()==0){
                    mEmptyLayout.setErrorType(EmptyLayout.NODATA);
                }else {
                    if(isClearDatas){
                        orderLists.clear();
                        orderDetails.clear();
                        orderAdapter.notifyDataSetChanged();
                    }

                    orderLists = entity.getList();

                    if(orderLists.size()==0){
                        isLastPage = true;
                        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.NODATA);
                        return;
                    }

                    for (int i = 0; i < orderLists.size(); i++) {
                        st++;
                        Order order = orderLists.get(i);
                        List<OrderDetail> orderDetailList = order.getDetailList();
                        Integer num = 0;
                        for(int k=0;k<orderDetailList.size();k++){
                            OrderDetail detail = orderDetailList.get(k);
                            num = num+ detail.getNum();
                        }
                        for(int k=0;k<orderDetailList.size();k++){
                            OrderDetail detail = orderDetailList.get(k);
                            if(k==0){
                                detail.setFirst(true);
                            }
                            if(k==orderDetailList.size()-1){
                                detail.setLast(true);
                            }
                            detail.setOrderNum(order.getOrderNo());
                            detail.setAmount(order.getAmount());
                            detail.setOrderAcount(num);
                            detail.setLogisticsCode(order.getLogisticsCode());
                            detail.setOrderStatus(order.getStatus());
                            detail.setCreateTime(order.getCreateTime());
                        }
                        orderDetails.addAll(order.getDetailList());
                    }

                    orderAdapter.notifyDataSetChanged();
                    pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                }

            }
        };
        String params = "";
        if(status==0){
            params = "userId=" + userId+"&st="+st;
        }else{
            params =  "userId=" + userId+"&status="+status+"&st="+st;
        }
        OKUtilAPI.post(OKUtilAPI.orderList, params, okUtilCallback);
    }


    @Override
    protected void initData() {
        orderAdapter = new OrderAdapter(orderDetails,getActivity(),status);
        pullableListView.setAdapter(orderAdapter);
        status =  (Integer)this.getArguments().get("fragmentId");
        requestData(true,true,true);
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {

        mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                st = 0;
                isLastPage = false;
                requestData(false,true,true);
            }
        });
        mEmptyLayout.setNoDataContent(BaseApplication.resources().getString(R.string.no_order));

        mEmptyLayout.setOnClickListener(this);
        pullToRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
//                loadData(1, AppConfig.PAGE_SIZE_1,
//                        userId, orderState,hasDiscuss, UIHelper.LISTVIEW_ACTION_REFRESH);
                st = 0;
                isLastPage = false;
                requestData(false,true,false);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                if (!isLastPage) {
                    requestData(false,false,false);
                } else {
                    pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.NODATA);
                }
                ;
            }
        });
        pullableListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                OrderDetail orderDetail = orderDetails.get(position);
                Intent intent = new Intent(OrderListFragment.this.getActivity(),OrderDetailActivity.class);
                intent.putExtra("orderId",orderDetail.getOrderId());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        st = 0;
        isLastPage = false;
        requestData(false,true,true);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.order_list_fragment;
    }

    @Override
    public void onRefresh() {
        st = 0;
        isLastPage = false;
        requestData(false,true,false);
    }
}

